import axios from 'axios';
import { message } from 'antd';
import storage from './storageUtils';

axios.interceptors.request.use(
  (req) => {
    const token = storage.getStorage('token');
    if (token) {
      // console.log(req);
      req.headers.Authentication = token;
    }
    return req;
  },
  (err) => Promise.reject(err),
);

axios.interceptors.response.use(
  (req) => {
    return req.data;
  },
  (err) => {
    const response = err.response;
    if (response) {
      switch (response.status) {
        case 500:
          message.error('服务器异常，稍后再试');
          break;
        case 401:
          message.error('身份认证过期，请重新登录');
          localStorage.removeItem('userInfo');
          localStorage.removeItem('token');
          window.location.href = '/login';
          break;
        case 404:
          message.error('请求路径发生变化');
          break;
        default:
          break;
      }
    }
    return Promise.reject(err);
  },
);
